package com.gaoding.qa.auto.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.http.HttpStatus;
import com.dtflys.forest.interceptor.Interceptor;
import com.gaoding.commons.util.SpringUtil;
import com.gaoding.qa.auto.config.RuntimeContext;
import com.gaoding.qa.auto.data.TestJavaObject;
import com.gaoding.qa.auto.help.TestHelper;
import com.gaoding.qa.auto.properties.GlobalProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 核心拦截器
 *
 * @author mobai
 * @since 2021/10/13 11:01
 */
@Configuration
@Slf4j
public class CoreInterceptor implements Interceptor<String> {
    public static final Map<Object, TestJavaObject> MAP = new ConcurrentHashMap<>();

    @Resource
    private GlobalProperties globalProperties;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        RuntimeContext context = TestHelper.getContext();
        if (!context.isIntercept()) {
            return true;
        }
        GlobalProperties globalProperties = SpringUtil.getBean(GlobalProperties.class);
        globalProperties.getHeaders().forEach(request::addHeader);
        Map<String, String> dynamicHeaders = context.getDynamicHeaders();
        dynamicHeaders.forEach(request::addHeader);
        return true;

    }

    @Override
    public void afterExecute(ForestRequest request, ForestResponse response) {
        log.info("\r\n 响应信息:[{}] \r\n 状态码:[{}] \r\n 预期值:[{}]\r\n 请求url:[{}]\r\n 请求body:[{}] \r\n 请求头:[{}]", response.getContent(), response.getStatusCode()
                , TestHelper.getContext().getStatus(), request.getUrl(), request.getBody()
                , request.getHeaders().entrySet().toArray());
        if (response.getStatusCode()!= HttpStatus.OK){
            Stack<RuntimeContext.ResponseError> error = TestHelper.getContext().getError();
            try {
                RuntimeContext.ResponseError responseError=new RuntimeContext.ResponseError();
                JSONObject jsonObject = JSON.parseObject(response.getContent());
                responseError.setCode(jsonObject.get("code").toString());
                responseError.setMessage(jsonObject.getString("message"));
                responseError.setError(jsonObject.get("error"));
                error.push(responseError);
            }catch (Exception e){
                log.error("请求异常,获取code&message失败");
            }
        }
    }


    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        log.error("请求失败,状态码:[{}]\r\n 错误信息:[{}] \r\n 错误原因:{}"
                , response.getStatusCode(), ex.getMessage(), ex);
    }

}
